package org.example.mock;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.MovieCountryAvg;

import java.sql.*;
import java.util.*;

/**
 * 用于生成 MovieCountryAvg 模拟数据的生成器类，适配对应数据库表结构
 */
@Slf4j
public class MovieCountryAvgGenerator {
    private static final String DB_URL = "jdbc:mysql://192.168.10.102/changchengfilm?requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;
    // 存储生成的 MovieCountryAvg 数据，便于后续使用，若不需要可根据实际情况调整
    private static final List<MovieCountryAvg> MOVIE_COUNTRY_AVG_LIST = new ArrayList<>();
    private static final Random RANDOM = new Random();
    // 存储countries表中的有效country_id
    private static List<Integer> validCountryIds = new ArrayList<>();

    public static void main(String[] args) {
        log.info("开始生成 MovieCountryAvg 模拟数据");

        // 初始化有效国家ID列表
        initValidCountryIds();

        if (validCountryIds.isEmpty()) {
            log.error("countries表中没有可用的country_id，请先确保countries表有数据");
            return;
        }

        // 计算可生成的最大记录数（受限于countries表的记录数）
        int maxCount = Math.min(100, validCountryIds.size());
        List<MovieCountryAvg> dataList = generateMovieCountryAvgData(maxCount);
        log.info("MovieCountryAvg 模拟数据生成完成，共生成 {} 条数据", dataList.size());

        // 插入数据到数据库
        insertDataToDatabase(dataList);
    }

    /**
     * 从countries表获取有效country_id
     */
    private static void initValidCountryIds() {
        String sql = "SELECT country_id FROM countries";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                validCountryIds.add(rs.getInt("country_id"));
            }

            log.info("已加载 {} 个有效country_id", validCountryIds.size());

        } catch (SQLException e) {
            log.error("获取countries表数据失败", e);
        }
    }

    /**
     * 生成指定数量的 MovieCountryAvg 模拟数据
     * @param count 要生成的数据数量
     * @return 包含生成的 MovieCountryAvg 对象的列表
     */
    private static List<MovieCountryAvg> generateMovieCountryAvgData(int count) {
        List<MovieCountryAvg> resultList = new ArrayList<>();

        if (validCountryIds.isEmpty() || count <= 0) {
            log.warn("无法生成数据：没有可用的country_id或生成数量为0");
            return resultList;
        }

        // 复制有效ID列表并打乱顺序
        List<Integer> shuffledCountryIds = new ArrayList<>(validCountryIds);
        Collections.shuffle(shuffledCountryIds, RANDOM);

        // 从打乱的列表中按顺序选取前count个ID，确保唯一性
        int generatedCount = 0;
        for (int countryId : shuffledCountryIds) {
            if (generatedCount >= count) {
                break;
            }

            // 生成随机平均评分，范围可根据实际情况调整，这里假设是 0 到 10 分，保留1位小数
            double randomAvgScore = Math.round(RANDOM.nextDouble() * 10 * 10) / 10.0;
            int totalMovies = RANDOM.nextInt(200) + 10; // 生成 10 到 209 之间的电影总数，可调整范围

            MovieCountryAvg data = new MovieCountryAvg(countryId, randomAvgScore, totalMovies);

            resultList.add(data);
            MOVIE_COUNTRY_AVG_LIST.add(data);
            generatedCount++;
        }

        if (generatedCount < count) {
            log.warn("countries表中的记录数量不足，只生成了 {} 条记录（请求 {} 条）", generatedCount, count);
        }

        return resultList;
    }

    /**
     * 将生成的数据批量插入到数据库
     * @param dataList 要插入的数据列表
     */
    private static void insertDataToDatabase(List<MovieCountryAvg> dataList) {
        // 使用ON DUPLICATE KEY UPDATE避免主键冲突（可选方案）
        String sql = "INSERT INTO movie_country_avg (country_id, avg_score, total_movies) VALUES (?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            conn.setAutoCommit(false); // 开启事务

            for (int i = 0; i < dataList.size(); i++) {
                MovieCountryAvg data = dataList.get(i);
                pstmt.setInt(1, data.getCountryId());
                pstmt.setDouble(2, data.getAvgScore());
                pstmt.setInt(3, data.getTotalMovies());
                pstmt.addBatch();

                // 每BATCH_SIZE条数据执行一次批处理
                if ((i + 1) % BATCH_SIZE == 0) {
                    pstmt.executeBatch();
                    conn.commit();
                    log.info("已插入 {} 条数据", i + 1);
                }
            }

            // 处理剩余数据
            pstmt.executeBatch();
            conn.commit();
            log.info("全部 {} 条数据已成功插入数据库", dataList.size());

        } catch (SQLException e) {
            log.error("数据库插入异常", e);
        }
    }
}